package handler

import (
	"github.com/gin-gonic/gin"
	"go-devops/common"
	"go-devops/domain/model"
	"log"
)

var TaskConnMap = model.NewTaskConnMap()

func ConnSSE(c *gin.Context) {
	c.Header("Content-Type", "text/event-stream")
	c.Header("Cache-Control", "no-cache")
	c.Header("Connection", "keep-alive")
	c.Header("Access-Control-Allow-Origin", "*")
	taskId, ok := c.GetQuery("taskId")
	if !ok {
		common.BizError(c, "参数异常")
		return
	}
	log.Println("ConnSSE taskId:", taskId)

	id, ok := c.GetQuery("id")
	if !ok || len(id) <= 0 {
		id = common.NewUUID()
	}
	log.Println("ConnSSE id:", id)

	stream := &model.SseStream{Writer: c.Writer, Id: id}

	taskMap := TaskConnMap.Get(taskId)
	if taskMap == nil {
		taskMap = model.NewSseClientMap()
		taskMap.Set(id, stream)
		TaskConnMap.Set(taskId, taskMap)
	} else {
		taskMap.Set(id, stream)
	}

	event := model.SseEvent{
		Data: model.MsgBuild(model.SUCCESS, true, "VM-DEVOPS"),
	}
	stream.Send(event)

	defer clearTaskConn(taskId, id)

	<-c.Done()
}

func CloseSSE(c *gin.Context) {
	taskId, ok := c.GetQuery("taskId")
	if !ok {
		common.BizError(c, "参数异常")
		return
	}

	id, ok := c.GetQuery("id")
	if !ok {
		common.BizError(c, "参数异常")
		return
	}

	go clearTaskConn(taskId, id)
	common.OK(c)
}

func clearTaskConn(taskId string, id string) {
	log.Println("close sse client taskId:"+taskId, " id:"+id)
	taskMap := TaskConnMap.Get(taskId)
	if taskMap == nil {
		return
	}
	taskMap.Delete(id)
}
